package gui;

import iCalImport.SaveDialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import net.sf.nachocalendar.CalendarFactory;
import net.sf.nachocalendar.components.CalendarPanel;
import tools.AppleTools;
import tools.MacOSXAboutHandler;
import tools.MacOSXPrefHandler;
import tools.OptionReader;
import cal.MonthData;
import cal.WeekData;
import calendar.Calendar;
import calendar.CheckboxCalendar;

import com.apple.eawt.Application;
import com.apple.eawt.event.GestureAdapter;
import com.apple.eawt.event.SwipeEvent;

import contacts.Adressbuch;
import contacts.CheckboxBook;
import contacts.Importer;
import contacts.VCardImportWindow;

/**
 * Hauptklasse die gestartet wird
 * 
 * @author Michi
 * 
 */
public class Test extends JFrame {

	/**
	 * Member Data
	 */
	private static final long serialVersionUID = -6995714852223129476L;
	private static Connection connection = tools.createConnection.connect();

	public static Connection getConnection() {
		return connection;
	}

	private JPanel contentPane;
	CalendarPanel calendarpanel;
	Adressbuch ab = new Adressbuch("Adressbuch");
	private JTextField countNewMailsTextField;
	private JTextField countNewEventsTextField;
	private JTextField countNewTasksTextField;

	JTabbedPane tabbedPane;
	private ToDoPane ToDo;
	private AddContactPane Kontakte;
	private JPanel kalender;
	private String user = "franz";
	private String pwd = "qwe";
	public static int iduser = 0;
	private int countermails;
	private String os = "os.name";
	private Properties prop = System.getProperties();
	private String opsys = prop.getProperty(os);
	private String osx = "Mac OS X";
	private String win7 = "Windows 7";
	private static JPanel loadingPanel;
	private JPanel checkBoxGroundPanel;
	private JScrollPane checkBoxGroundPanelScrollPane;
	private JProgressBar progressBar;
	private JPanel leftSideGroundPanel;
	private static Test mainInstance;

	public static Test getMainInstance() {
		return mainInstance;
	}

	@SuppressWarnings("static-access")
	public void setMainInstance(Test mainInstance) {
		this.mainInstance = mainInstance;
	}

	private JButton addCalendar;
	private JButton addBook;
	private JButton removeCalendar;
	private JButton removeBook;
	private JScrollPane checkboxlistCalendarScroll;
	private JScrollPane checkboxlistBooksScroll;
	private CheckBoxList checkboxlistCalendar;
	private CheckBoxList checkboxlistBooks;
	private DefaultListModel dlmCalendar;
	private DefaultListModel dlmBooks;
	private LinkedList<Integer> ids = new LinkedList<Integer>();
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;
	private Date nachoTempDate = new Date();
	private int speak = 0;
	private Date click;

	// SortedToDo (0 = nach datum, 1 = nach erledigt)
	private int sortedToDo = 0;

	@SuppressWarnings("unused")
	private int zuerstDatumToDo = 0;

	// Sprachen (0 = deutsch; 1 = englisch; 2 = latein)

	String[] adressbuch = { "Adressbuch", "Directory", "Allocutio Libro" };
	String[] neuerTermin = { "Neuer Termin", "New Event", "Nominationis" };
	String[] neuerKontakt = { "Neuer Kontakt", "New Contact",
			"Novam  Contactus" };
	String[] datei = { "Datei", "File", "Rei" };
	String[] optionen = { "Optionen", "Options", "Praeferentiae" };
	String[] schliessen = { "Schliessen", "Exit", "Claudere" };
	String[] neu = { "Neu", "New", "Novum" };
	String[] neuerKalender = { "Neuer Kalender", "New Calendar",
			"Novum Calendarium" };
	String[] neuerPerson = { "Neue Person", "New Person", "Novum Hominem" };
	String[] neueAufgabe = { "Neue Aufgabe", "New Task", "Novam Negotium" };
	String[] neueMail = { "Neue E-Mail", "New Mail", "Novam Litteras" };
	String[] importieren = { "Importieren", "Import", "Importere" };
	String[] vcardimportieren = { "vCard Importieren", "Import vCard",
			"Importere vKartus" };
	String[] icalimportieren = { "iCal Importieren", "Import iCal",
			"Importere iCalius" };
	String[] exportstring = { "Exportieren", "Export", "Exportere" };
	String[] vcardexport = { "vCard exportieren", "Export vCard",
			"Exportere vKartus" };
	String[] hilfe = { "Hilfe", "Help", "Auxilium" };
	String[] fboHilfe = { "Fireball Organizer Hilfe",
			"Fireball Organizer Help", "Fireball Organizer Auxilium" };

	String[] laden = { "Wird geladen...", "Loading...", "Imponere..." };

	String[] kalenderR = { "Kalender", "Calendar", "Calendarium" };
	String[] kontakte = { "Kontakte", "Contacts", "Contactus" };
	String[] todo = { "Aufgaben", "Tasks", "Negotium" };
	String[] mail = { "E-Mail", "Mail", "Litteras" };
	
	String[] gotoCal ={"Öffnet Kalender", "Opens calendar", "Calendarium Meretrix"};
	String[] gotoMail = {"Öffnet Mails", "Opens mail", "Litteras Meretrix"};
	String[] gotoTask = {"Öffnet Aufgaben", "Opens tasks", "Fornicariam Meretrix"};
	
	String[] addCal = {"Neuen Kalender erstellen", "Add calendar", "Calendarium addere"};
	String[] deleteCal = {"Kalender löschen", "Delete calendar", "Calendrium extinguere"};
	
	String[] addBooks = {"Neues Adressbuch erstellen", "Add adress book", "Index Domicilorum addere"};
	String[] deleteBook = {"Adressbuch löschen", "Delete adress book", "Index Domicilorum extinguere"};

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Test.iduser = 2;
					Test frame = new Test();
					frame.setVisible(true);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	@SuppressWarnings({ "static-access", "deprecation" })
	public Test() {

		System.out.println(Test.iduser);
		mainInstance = this;

		// OptionRead Test
		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}
		if (or.getCalOptStandardView().equals("week")) {
			setKalender(new WeekView(mainInstance, new Date()));

		} else {
			kalender = new CalView(mainInstance);

		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);
		speak = Integer.parseInt(or.getLanguage());
		sortedToDo = Integer.parseInt(or.getToDoOpt1());
		zuerstDatumToDo = Integer.parseInt(or.getToDoOpt2());

		// OptionRead Test Ende
		Kontakte = new AddContactPane();
		ToDo = new ToDoPane();
		viewMail = new ViewMail(mainInstance);

		setTitle("Fireball Organizer");
		if (osx.equals(opsys)) {

			Application application = Application.getApplication();
			Image image = Toolkit.getDefaultToolkit().getImage(
					"src/pictures/fireball.png");
			application.setDockIconImage(image);

			enableFullScreenMode(this);
			this.getRootPane().getGlassPane().setEnabled(true);
			this.getRootPane().getGlassPane().setVisible(true);

			AppleTools.addGestureListenerTo(this.getRootPane().getGlassPane(),
					new GestureAdapter() {

						public void swipedLeft(SwipeEvent sw) {
							System.out.println("links");
						}

						public void swipedRight(SwipeEvent sw) {
							System.out.println("rechts");
						}

					});

			// Dock Menu Anfang
			application.setDockMenu(new PopupMenu("DockMenu"));
			MenuItem newMail = new MenuItem(neueMail[speak]);
			newMail.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					new NewMailWindow().setVisible(true);

				}

			});
			application.getDockMenu().add(newMail);

			MenuItem newEvent = new MenuItem(neuerTermin[speak]);
			newEvent.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					new NewEventWindow().setVisible(true);

				}

			});
			application.getDockMenu().add(newEvent);

			MenuItem newPerson = new MenuItem(neuerKontakt[speak]);
			newPerson.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					new NewContactWindow().setVisible(true);

				}

			});
			application.getDockMenu().add(newPerson);
			// Dock Menu Ende

			// About Fenster anpassen
			@SuppressWarnings("unused")
			MacOSXAboutHandler ah = new MacOSXAboutHandler();
			@SuppressWarnings("unused")
			MacOSXPrefHandler ph = new MacOSXPrefHandler();

			// lässt das dock icon hüpfen --> neue email
			// application.requestUserAttention(true);

			try {
				System.setProperty("apple.laf.useScreenMenuBar", "true");
				System.setProperty(
						"com.apple.mrj.application.apple.menu.about.name",
						"AppName");
				UIManager.setLookAndFeel(UIManager
						.getSystemLookAndFeelClassName());

			} catch (Exception e) {
				// Fehlerbehandlung
			}
		}

		if (win7.equals(opsys)) {

			setIconImage(Toolkit.getDefaultToolkit().getImage(
					"src/pictures/fireball.png"));

		}

		// Standart Einstellungen

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(1300, 710);
		// TODO

		// setBounds(100, 100, 450, 300);

		// ----------------------------------------ANFANG---MENÜ---SECTION------------------------------------------------->
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		// Definition vom Reiter "Datei"
		JMenu mnDatei = new JMenu(datei[speak]);

		// MenüItem Optionen - ruft das Optionen Fenster auf
		JMenuItem mntmOptionen = new JMenuItem(optionen[speak]);

		if (osx.equals(opsys)) {
			mntmOptionen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
					Event.META_MASK));

			mntmOptionen.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					new OptionsTest().setVisible(true);
				}
			});
		}

		if (!osx.equals(opsys)) {
			mntmOptionen.setMnemonic(KeyEvent.VK_O);
			mntmOptionen.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					new OptionsTest().setVisible(true);

				}
			});
			menuBar.add(mnDatei);
			mnDatei.add(mntmOptionen);
		}

		if (!osx.equals(opsys)) {
			// MenüItem Schließen - Schließt die Anwendung
			JMenuItem mntmSchliessen = new JMenuItem(schliessen[speak]);
			mntmSchliessen.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					dispose();
				}
			});
			mnDatei.add(mntmSchliessen);
		}

		// Menü Reiter Neu
		JMenu mnNeu = new JMenu(neu[speak]);
		menuBar.add(mnNeu);

		// Menü Item Neuer Kalender - ruft Funktiona auf um einen neuen
		// Kalender
		// anzulegen
		JMenuItem mntmNeuerKalender = new JMenuItem(neuerKalender[speak]);
		if (osx.equals(opsys)) {
			mntmNeuerKalender.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_K, Event.META_MASK));

			mntmNeuerKalender.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					NewCalendarWindow nc = new NewCalendarWindow(mainInstance);
					nc.setVisible(true);
				}
			});
		}
		mntmNeuerKalender.setMnemonic(KeyEvent.VK_K);

		mntmNeuerKalender.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				NewCalendarWindow nc = new NewCalendarWindow(mainInstance);
				nc.setVisible(true);
			}
		});

		mnNeu.add(mntmNeuerKalender);

		// MenüItem Neue Person - ruft Funktion auf um einen kontakt
		// hinzuzufügen
		JMenuItem mntmNeuePerson = new JMenuItem(neuerPerson[speak]);

		if (osx.equals(opsys)) {
			mntmNeuePerson.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,
					Event.META_MASK));

			mntmNeuePerson.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					new NewContactWindow().setVisible(true);

				}
			});
		}
		mntmNeuePerson.setMnemonic(KeyEvent.VK_P);

		mntmNeuePerson.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				System.out.println("fine");
				Importer imp = new Importer();
				ab.addPerson(imp.getFiles(), null);
			}
		});

		mnNeu.add(mntmNeuePerson);

		// MenüItem neues Event - ruft Funktion auf um neues
		// Event/Termin
		// anzulegen
		JMenuItem mntmNeuesEvent = new JMenuItem(neuerTermin[speak]);
		if (osx.equals(opsys)) {
			mntmNeuesEvent.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
					Event.META_MASK));

			mntmNeuesEvent.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					NewEventWindow ne = new NewEventWindow();
					ne.setVisible(true);
				}
			});
		}
		mntmNeuesEvent.setMnemonic(KeyEvent.VK_E);

		mntmNeuesEvent.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				NewEventWindow ne = new NewEventWindow();
				ne.setVisible(true);
			}
		});

		mnNeu.add(mntmNeuesEvent);

		// MenüItem Neue Aufgabe - ruft Funktion auf um einen neuen Task
		// anzulegen
		JMenuItem mntmNeueAufgabe = new JMenuItem(neueAufgabe[speak]);
		if (osx.equals(opsys)) {
			mntmNeueAufgabe.setAccelerator(KeyStroke.getKeyStroke(
					KeyEvent.VK_T, Event.META_MASK));

			mntmNeueAufgabe.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					NewTaskWindow nt = new NewTaskWindow(null);
					nt.setVisible(true);
				}
			});
		}
		mntmNeueAufgabe.setMnemonic(KeyEvent.VK_T);

		mntmNeueAufgabe.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				NewTaskWindow nt = new NewTaskWindow(null);
				nt.setVisible(true);
			}
		});

		mnNeu.add(mntmNeueAufgabe);

		// Reiter Importieren
		JMenu mnImportieren = new JMenu(importieren[speak]);
		menuBar.add(mnImportieren);

		JMenuItem importCal = new JMenuItem(icalimportieren[speak]);
		if (osx.equals(opsys)) {
			importCal.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					new SaveDialog(mainInstance).setVisible(true);

				}

			});
		} else {
			importCal.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					SaveDialog sd = new SaveDialog(mainInstance);
					sd.setVisible(true);
				}
			});
		}

		mnImportieren.add(importCal);
		JMenuItem importCon = null;
		if (osx.equals(opsys)) {
			importCon = new JMenuItem(vcardimportieren[speak]);
			importCon.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {

					new VCardImportWindow().setVisible(true);
				}

			});
		} else {

			importCon = new JMenuItem(vcardimportieren[speak]);
			importCon.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					new VCardImportWindow().setVisible(true);
				}
			});
		}
		mnImportieren.add(importCon);

		JMenu exportieren = new JMenu(exportstring[speak]);

		JMenuItem export = new JMenuItem(vcardexport[speak]);
		if (osx.equals(opsys)) {
			export.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent arg0) {
					System.out.println("jo");
					new AddContactWindow(new Boolean(""), false)
							.setVisible(true);

				}

			});
		} else {
			export.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					System.out.println("yo");
					new AddContactWindow(new Boolean(""), false)
							.setVisible(true);
				}
			});
		}
		menuBar.add(exportieren);
		exportieren.add(export);

		// Reiter Hilfe
		JMenu mnHilfe = new JMenu(hilfe[speak]);
		menuBar.add(mnHilfe);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(r, g, b));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		if (osx.equals(opsys)) {

			JMenuItem mntmOfflineHilfe = new JMenuItem(fboHilfe[speak]);
			mntmOfflineHilfe.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					new Help(mainInstance);
				}
			});
			mnHilfe.add(mntmOfflineHilfe);
		} else {

			JMenuItem mntmOfflineHilfe = new JMenuItem(fboHilfe[speak]);
			mntmOfflineHilfe.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					new Help(mainInstance);
				}
			});
			mnHilfe.add(mntmOfflineHilfe);
		}

		// ----------------------------------------ENDE---MENÜ---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--LEFT---PANEL---SECTION------------------------------------------------->

		// Panel, welches die Grundlage des linken Teil der Ansicht
		// bildet

		// Grundeinstellungen zum linken Grundlagen Panel

		leftSideGroundPanel = new JPanel();
		leftSideGroundPanel.setBackground(new Color(r, g, b));
		leftSideGroundPanel.setSize(new Dimension(250, 680));
		leftSideGroundPanel.setPreferredSize(new Dimension(250, 680));
		contentPane.add(leftSideGroundPanel, BorderLayout.WEST);
		leftSideGroundPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		// ----------------------------------------ANFANG--NOTIFY---PANEL---SECTION------------------------------------------------->

		JPanel notify = new JPanel();
		notify.setLayout(new BorderLayout(0, 0));
		leftSideGroundPanel.add(notify);

		// ----------------------------------------ANFANG--NOTIFY---OBEN---PANEL---SECTION------------------------------------------------->

		JPanel notifyOben = new JPanel();
		notifyOben.setPreferredSize(new Dimension(250, 50));
		notifyOben.setBackground(new Color(r, g, b));
		notify.add(notifyOben, BorderLayout.NORTH);

		// ----------------------------------------ANFANG--MAIL--ICON---PANEL---SECTION------------------------------------------------->
		// Mail Icon

		JButton MailIcon = new JButton();
		MailIcon.setToolTipText(gotoMail[speak]);
		// MailIcon.setBackground(new Color(r, g, b));
		MailIcon.setPreferredSize(new Dimension(50, 50));
		File MailImageFile = new File("src/pictures/Mailneu.png");
		BufferedImage MailImage = null;
		try {
			MailImage = ImageIO.read(MailImageFile);
			MailImage = (BufferedImage) resize(MailImage, 40, 40);
		} catch (IOException ioex) {
			// abort
			System.out.println("?");
			System.exit(1);
		}
		MailIcon.add(new JLabel(new ImageIcon(MailImage), JLabel.CENTER));
		MailIcon.setVisible(true);

		GridBagLayout gbl_buttonPanel = new GridBagLayout();
		gbl_buttonPanel.columnWidths = new int[] { 75, 75, 75 };
		gbl_buttonPanel.rowHeights = new int[] { 0, 0 };
		gbl_buttonPanel.columnWeights = new double[] { 0.0, 0.0, 0.0 };
		gbl_buttonPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };

		// notifyOben.setLayout(new GridLayout(0, 3, 0, 0));
		notifyOben.setLayout(gbl_buttonPanel);
		MailIcon.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				tabbedPane.setSelectedIndex(3);

			}
		});
		notifyOben.add(MailIcon);
		// ----------------------------------------ENDE--MAIL-ICON--PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--KALENDER--ICON---PANEL---SECTION------------------------------------------------->

		// Kalender Icon
		JButton KalenderIcon = new JButton();
		KalenderIcon.setToolTipText(gotoCal[speak]);
		// KalenderIcon.setBackground(new Color(r, g, b));
		KalenderIcon.setPreferredSize(new Dimension(50, 50));

		File CalImageFile = new File("src/pictures/Cal.png");
		BufferedImage CalImage = null;
		try {
			CalImage = ImageIO.read(CalImageFile);
			CalImage = (BufferedImage) resize(CalImage, 40, 40);
		} catch (IOException ioex) {
			// abort
			System.out.println("?");
			System.exit(1);
		}
		KalenderIcon.add(new JLabel(new ImageIcon(CalImage), JLabel.CENTER));
		KalenderIcon.setVisible(true);
		KalenderIcon.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				tabbedPane.setSelectedIndex(0);
			}
		});
		notifyOben.add(KalenderIcon);
		// ----------------------------------------ENDE--KALENDER--ICON---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--TASKS--ICON---PANEL---SECTION------------------------------------------------->

		// Tasks Icon
		JButton TasksIcon = new JButton();
		TasksIcon.setToolTipText(gotoTask[speak]);
		// TasksIcon.setBackground(new Color(r, g, b));
		TasksIcon.setPreferredSize(new Dimension(50, 50));

		File TaskImageFile = new File("src/pictures/Tasks.png");
		BufferedImage TaskImage = null;
		try {
			TaskImage = ImageIO.read(TaskImageFile);
			TaskImage = (BufferedImage) resize(TaskImage, 40, 40);
		} catch (IOException ioex) {
			// abort
			System.out.println("?");
			System.exit(1);
		}
		TasksIcon.add(new JLabel(new ImageIcon(TaskImage), JLabel.CENTER));
		TasksIcon.setVisible(true);
		TasksIcon.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				tabbedPane.setSelectedIndex(2);
			}
		});
		notifyOben.add(TasksIcon);

		// ----------------------------------------ENDE--TASKS--ICON---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ENDE--NOTIFY---OBEN---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--NOTIFY--UNTEN---PANEL---SECTION------------------------------------------------->

		JPanel notifyUnten = new JPanel();
		notifyUnten.setPreferredSize(new Dimension(250, 50));
		notifyUnten.setBackground(new Color(r, g, b));
		notify.add(notifyUnten, BorderLayout.SOUTH);
		notifyUnten.setLayout(new GridLayout(1, 0, 0, 0));

		countNewMailsTextField = new JTextField();
		countNewMailsTextField.setDisabledTextColor(Color.BLACK);
		countNewMailsTextField.setEnabled(false);
		countNewMailsTextField.setEditable(false);
		countNewMailsTextField.setHorizontalAlignment(SwingConstants.CENTER);

		viewMail.geteMailListGroundPanel().addContainerListener(
				new ContainerListener() {

					@Override
					public void componentAdded(ContainerEvent arg0) {
						// TODO Auto-generated method stub

					}

					@Override
					public void componentRemoved(ContainerEvent arg0) {
						countermails = 0;
						Date tempToday = new Date();
						for (int i = 0; i < viewMail.getLl().size(); i++) {
							if (viewMail.getLl().get(i).getSentDate().getDate() == tempToday
									.getDate()
									&& viewMail.getLl().get(i).getSentDate()
											.getMonth() == tempToday.getMonth()
									&& viewMail.getLl().get(i).getSentDate()
											.getYear() == tempToday.getYear()) {
								countermails++;
							}
						}
						countNewMailsTextField.setText(countermails + "");

					}

				});
		countermails = 0;
		Date tempToday = new Date();
		for (int i = 0; i < viewMail.getLl().size(); i++) {
			if (viewMail.getLl().get(i).getSentDate().getDate() == tempToday
					.getDate()
					&& viewMail.getLl().get(i).getSentDate().getMonth() == tempToday
							.getMonth()
					&& viewMail.getLl().get(i).getSentDate().getYear() == tempToday
							.getYear()) {
				countermails++;
			}
		}
		countNewMailsTextField.setText(countermails + "");
		// countNewMailsTextField.setText(viewMail.getLl().size() + "");
		notifyUnten.add(countNewMailsTextField);
		countNewMailsTextField.setColumns(10);

		countNewEventsTextField = new JTextField();
		countNewEventsTextField.setDisabledTextColor(Color.BLACK);
		countNewEventsTextField.setEditable(false);
		countNewEventsTextField.setEnabled(false);
		countNewEventsTextField.setHorizontalAlignment(SwingConstants.CENTER);

		if (kalender instanceof CalView) {
			countNewEventsTextField.setText(((CalView) kalender).getDayCount()
					+ "");
		} else {
			countNewEventsTextField.setText(((WeekView) kalender)
					.getAllCalendarItems().size() + "");

		}

		notifyUnten.add(countNewEventsTextField);

		countNewEventsTextField.setColumns(10);

		countNewTasksTextField = new JTextField();
		countNewTasksTextField.setEnabled(false);
		countNewTasksTextField.setEditable(false);
		countNewTasksTextField.setDisabledTextColor(Color.BLACK);
		countNewTasksTextField.setHorizontalAlignment(SwingConstants.CENTER);
		countNewTasksTextField.setText(((ToDoPane) ToDo).getTaskslinkedlist()
				.size() + "");
		notifyUnten.add(countNewTasksTextField);
		countNewTasksTextField.setColumns(10);

		// ----------------------------------------ENDE--NOTIFY--UNTEN---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ENDE--NOTIFY---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--MINI---CALENDAR---PANEL---SECTION------------------------------------------------->

		JPanel MiniCalendar = new JPanel();

		if (speak == 0) {
			Locale loc = Locale.GERMAN;
			MiniCalendar.setDefaultLocale(loc);
			Locale.setDefault(loc);
		}
		if (speak == 1) {
			Locale loc = Locale.ENGLISH;
			MiniCalendar.setDefaultLocale(loc);
			Locale.setDefault(loc);
		}
		if (speak == 2) {
			Locale loc = Locale.ITALY;
			MiniCalendar.setDefaultLocale(loc);
			Locale.setDefault(loc);
		}

		MiniCalendar.setBackground(new Color(r, g, b));
		MiniCalendar.setPreferredSize(new Dimension(250, 220));
		MiniCalendar.setMaximumSize(new Dimension(250, 300));
		MiniCalendar.setMinimumSize(new Dimension(164, 51));

		MiniCalendar.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {

				// System.out.println(calendarpanel.getValue());

			}
		});

		MiniCalendar.setBackground(new Color(238, 238, 238));
		leftSideGroundPanel.add(MiniCalendar);
		calendarpanel = CalendarFactory.createCalendarPanel(1);
		calendarpanel.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				if (calendarpanel.getValue().equals(getNachoTempDate())) {

					if (getKalender() instanceof CalView) {
						MonthData md = new MonthData();
						Date[] da = md.getDateArray((Date) calendarpanel
								.getValue());
						int k = 0;
						for (int i = 0; i < da.length; i++) {
							if (da[i].equals((Date) calendarpanel.getValue())) {
								k = i;
							}

						}

						new DayView((CalView) getKalender(),
								(DayPanel) ((CalView) getKalender())
										.getCalGroundPanel().getComponent(k))
								.setVisible(true);
					}

					if (getKalender() instanceof WeekView) {
						WeekData wd = new WeekData();
						Date[] da = wd.getDateArray((Date) calendarpanel
								.getValue());
						int k = 0;
						for (int i = 0; i < da.length; i++) {
							if (da[i].equals((Date) calendarpanel.getValue())) {
								k = i;
							}

						}

						new DayView((WeekView) getKalender(),
								(WeekDayPanel) ((WeekView) getKalender())
										.getWeekPanel().getComponent(k))
								.setVisible(true);

					}
				}

				setNachoTempDate((Date) calendarpanel.getValue());

				updateCalendar();

			}
		});

		MiniCalendar.setLayout(new BorderLayout(0, 0));
		MiniCalendar.add(calendarpanel);

		// ----------------------------------------ENDE--MINI---CALENDAR---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--CHECK---BOX--GROUND---PANEL---SECTION------------------------------------------------->
		checkBoxGroundPanel = new JPanel();
		checkBoxGroundPanelScrollPane = new JScrollPane(checkBoxGroundPanel);
		checkBoxGroundPanel.setSize(new Dimension(250, 100));
		checkBoxGroundPanel.setMinimumSize(new Dimension(250, 100));
		checkBoxGroundPanel.setMaximumSize(new Dimension(250, 100));
		checkBoxGroundPanel.setPreferredSize(new Dimension(250, 200));
		checkBoxGroundPanel.setBackground(new Color(r, g, b));

		// Liste mit Checkboxen fuer verchiedene Kalender
		checkboxlistCalendar = new CheckBoxList();
		// checkboxlistCalendar.setPreferredSize(new Dimension(250, 150));
		checkboxlistCalendar.setAlignmentY(Component.TOP_ALIGNMENT);
		checkboxlistCalendar.setAlignmentX(Component.LEFT_ALIGNMENT);
		dlmCalendar = new DefaultListModel();
		// checkboxlistCalendar.setVisibleRowCount(18);

		checkboxlistCalendarScroll = new JScrollPane(checkboxlistCalendar);
		checkboxlistCalendarScroll.setPreferredSize(new Dimension(250, 150));

		Icon iconHinzu = new ImageIcon("src/pictures/add.png");
		addCalendar = new JButton(iconHinzu);
		addCalendar.setToolTipText(addCal[speak]);
		// addCalendar.setText("+");

		Icon iconLoeschen = new ImageIcon("src/pictures/bin.png");
		removeCalendar = new JButton(iconLoeschen);
		removeCalendar.setToolTipText(deleteCal[speak]);
		// removeCalendar.setText("-");

		ActionListener newCal = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				NewCalendarWindow ncw = new NewCalendarWindow(mainInstance);
				ncw.setVisible(true);

			}
		};
		addCalendar.addActionListener(newCal);

		ActionListener deleteCal = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				DeleteCalendarsWindow dcw = new DeleteCalendarsWindow(
						mainInstance);
				dcw.setVisible(true);

			}
		};
		removeCalendar.addActionListener(deleteCal);

		// Liste mit Checkboxen fuer verschiedene Kontaktbuecher
		checkboxlistBooks = new CheckBoxList();
		// checkboxlistBooks.setPreferredSize(new Dimension(250, 150));
		checkboxlistBooks.setAlignmentY(Component.TOP_ALIGNMENT);
		checkboxlistBooks.setAlignmentX(Component.LEFT_ALIGNMENT);
		dlmBooks = new DefaultListModel();
		// checkboxlistBooks.setVisibleRowCount(18);

		checkboxlistBooksScroll = new JScrollPane(checkboxlistBooks);
		checkboxlistBooksScroll.setPreferredSize(new Dimension(250, 150));

		addBook = new JButton(iconHinzu);
		addBook.setToolTipText(addBooks[speak]);
		// addBook.setText("+");
		removeBook = new JButton(iconLoeschen);
		removeBook.setToolTipText(deleteBook[speak]);
		// removeBook.setText("-");

		ActionListener newBook = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				NewBookWindow nbw = new NewBookWindow(mainInstance);
				nbw.setVisible(true);

			}
		};
		addBook.addActionListener(newBook);

		ActionListener deleteBook = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				DeleteBooksWindow dbw = new DeleteBooksWindow(mainInstance);
				dbw.setVisible(true);

			}
		};
		removeBook.addActionListener(deleteBook);

		// Verbindung zur Datenbank herstellen

		Timer time = new Timer();
		time.scheduleAtFixedRate(new checkforInvites(), new Date(), 10000);

		ResultSet calendars = null;
		ResultSet books = null;

		try {
			calendars = getCalendarsFromDB();
			books = getBooksFromDB();
			while (calendars.next()) {
				CheckboxCalendar calendar = new CheckboxCalendar(
						calendars.getInt("idCalendar"),
						calendars.getString("name"),
						calendars.getInt("idCreator"));

				JCheckBoxWithObject check = new JCheckBoxWithObject(calendar);
				dlmCalendar.addElement(check);
			}

			while (books.next()) {
				CheckboxBook book = new CheckboxBook(books.getInt("idBooks"),
						books.getString("name"), books.getInt("idCreator"));
				JCheckBoxWithObject check = new JCheckBoxWithObject(book);
				dlmBooks.addElement(check);
			}
		} catch (SQLException e1) {
			JOptionPane
					.showMessageDialog(
							null,
							"Es konnte keine Verbindung zur Datenbank hergestellt werden",
							"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}

		MouseListener checklisten = new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {

				if (e.getClickCount() == 1) {

					updateLeftPane(false);
				}
				// if (tabbedPane.getSelectedIndex() == 0
				// || tabbedPane.getSelectedIndex() == 2) {
				// if (e.getClickCount() == 2) {
				//
				// JCheckBoxWithObject current = (JCheckBoxWithObject)
				// dlmCalendar
				// .get(checkboxlistCalendar.getSelectedIndex());
				// CheckboxCalendar currentcal = (CheckboxCalendar) current
				// .getObject();
				// EditCalendar ec = new EditCalendar(mainInstance,
				// currentcal);
				// ec.setVisible(true);
				// }
				// }
				//
				// if (tabbedPane.getSelectedIndex() == 1) {
				// if (e.getClickCount() == 2) {
				//
				// JCheckBoxWithObject current = (JCheckBoxWithObject) dlmBooks
				// .get(checkboxlistBooks.getSelectedIndex());
				// CheckboxBook currentcal = (CheckboxBook) current
				// .getObject();
				// EditBooks eb = new EditBooks(mainInstance, currentcal);
				// eb.setVisible(true);
				// }
				// }

			}

			public void mousePressed(MouseEvent e) {

				if (tabbedPane.getSelectedIndex() == 0
						|| tabbedPane.getSelectedIndex() == 2) {
					evaluatePopupCal(e);

				}

				if (tabbedPane.getSelectedIndex() == 1) {
					evaluatePopupBook(e);

				}

			}

			public void mouseReleased(MouseEvent e) {
				if (tabbedPane.getSelectedIndex() == 0
						|| tabbedPane.getSelectedIndex() == 2) {
					evaluatePopupCal(e);

				}

				if (tabbedPane.getSelectedIndex() == 1) {
					evaluatePopupBook(e);

				}

			}
		};

		checkboxlistCalendar.setModel(dlmCalendar);
		checkboxlistBooks.setModel(dlmBooks);

		checkboxlistCalendar.selectAll();
		checkboxlistBooks.selectAll();

		checkboxlistCalendar.setVisible(true);
		checkboxlistBooks.setVisible(false);
		checkboxlistCalendarScroll.setVisible(true);
		checkboxlistBooksScroll.setVisible(false);
		addCalendar.setVisible(true);
		addBook.setVisible(false);
		removeCalendar.setVisible(true);
		removeBook.setVisible(false);

		checkboxlistCalendar.addMouseListener(checklisten);
		checkboxlistBooks.addMouseListener(checklisten);

		checkBoxGroundPanel.add(checkboxlistCalendarScroll);
		checkBoxGroundPanel.add(checkboxlistBooksScroll);
		checkBoxGroundPanel.add(addBook);
		checkBoxGroundPanel.add(addCalendar);
		checkBoxGroundPanel.add(removeCalendar);
		checkBoxGroundPanel.add(removeBook);

		leftSideGroundPanel.add(checkBoxGroundPanelScrollPane);

		// ----------------------------------------ENDE--CHECK---BOX--GROUND---PANEL---SECTION------------------------------------------------->

		// -----------------------------------------ANFANG-------LOADING--PANEL--------------------------------------------------->
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				// TODO
				loadingPanel = new JPanel();
				loadingPanel.setBackground(new Color(r, g, b));
				loadingPanel.setSize(new Dimension(250, 50));
				loadingPanel.setPreferredSize(new Dimension(250, 120));
				loadingPanel.setMinimumSize(new Dimension(250, 50));
				loadingPanel.setMaximumSize(new Dimension(250, 50));

				leftSideGroundPanel.add(loadingPanel);
				progressBar = new JProgressBar();
				progressBar.setBackground(new Color(r, g, b));
				Border border = BorderFactory.createTitledBorder(laden[speak]);
				loadingPanel.setLayout(new GridLayout(0, 1, 0, 0));

				JPanel dummyPanel1 = new JPanel();
				dummyPanel1.setBackground(new Color(r, g, b));
				dummyPanel1.setVisible(false);
				dummyPanel1.setPreferredSize(new Dimension(249, 60));
				loadingPanel.add(dummyPanel1);
				progressBar.setBorder(border);
				progressBar.setSize(new Dimension(230, 45));
				progressBar.setMaximumSize(new Dimension(230, 50));
				progressBar.setMinimumSize(new Dimension(230, 50));
				progressBar.setPreferredSize(new Dimension(50, 50));
				progressBar.setIndeterminate(true);
				progressBar.setStringPainted(false);
				loadingPanel.add(progressBar);
				progressBar.setVisible(false);
			}
		});

		// -----------------------------------------ENDE-------LOADING--PANEL--------------------------------------------------->

		// ----------------------------------------ENDE--LEFT---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--RIGHT----TABBED---PANEL---SECTION------------------------------------------------->

		//

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		contentPane.add(tabbedPane, BorderLayout.CENTER);

		// ----------------------------------------ANFANG--KALENDER---PANEL---SECTION------------------------------------------------->

		tabbedPane.add(kalenderR[speak], kalender);

		// ----------------------------------------ENDE--KALENDER---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--KONTAKTE---PANEL---SECTION------------------------------------------------->
		tabbedPane.add(kontakte[speak], Kontakte);

		// ----------------------------------------ENDE--KONTAKTE---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--TASK---PANEL---SECTION------------------------------------------------->

		tabbedPane.add(todo[speak], ToDo);

		// ----------------------------------------ENDE--TASK---PANEL---SECTION------------------------------------------------->

		// ----------------------------------------ANFANG--EMAIL---PANEL---SECTION------------------------------------------------->

		tabbedPane.add(mail[speak], viewMail);

		// ----------------------------------------ENDE--EMAIL---PANEL---SECTION------------------------------------------------->

		for (int i = 0; i < dlmCalendar.size(); i++) {
			JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmCalendar.get(i);
			if (temp.isSelected() == true) {
				CheckboxCalendar temp2 = (CheckboxCalendar) temp.getObject();
				ids.add(temp2.getIdCalendar());
			}
		}

		try {
			idIntoLokalDB(ids);
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e1) {
			JOptionPane
					.showMessageDialog(
							null,
							"Es konnte keine Verbindung zur Datenbank hergestellt werden",
							"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}

		if (sortedToDo == 0) {
			ToDo.update();
		}
		if (sortedToDo == 1) {
			ToDo.updateSorted();
		}

		Kontakte.update();

		if (mainInstance.getKalender() instanceof CalView) {
			System.out.println("MONAT");
			((CalView) kalender).createCal(new Date());
		} else if (mainInstance.getKalender() instanceof WeekView) {
			System.out.println("WOCHE!");
			((WeekView) kalender).createWeekView();
		}

		ChangeListener tabchange = new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				if (tabbedPane.getSelectedIndex() == 0) {
					checkboxlistCalendar.setVisible(true);
					checkboxlistBooks.setVisible(false);
					addCalendar.setVisible(true);
					addBook.setVisible(false);
					checkboxlistCalendarScroll.setVisible(true);
					checkboxlistBooksScroll.setVisible(false);
					removeCalendar.setVisible(true);
					removeBook.setVisible(false);

					ids.clear();
					for (int i = 0; i < dlmCalendar.size(); i++) {
						JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmCalendar
								.get(i);
						if (temp.isSelected() == true) {
							CheckboxCalendar temp2 = (CheckboxCalendar) temp
									.getObject();
							ids.add(temp2.getIdCalendar());
						}
					}

					try {
						idIntoLokalDB(ids);
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						JOptionPane
								.showMessageDialog(
										null,
										"Es konnte keine Verbindung zur Datenbank hergestellt werden",
										"Haaalt! Stop!",
										JOptionPane.ERROR_MESSAGE);
						e1.printStackTrace();
					}

				} else if (tabbedPane.getSelectedIndex() == 1) {
					checkboxlistCalendar.setVisible(false);
					checkboxlistBooks.setVisible(true);
					addCalendar.setVisible(false);
					addBook.setVisible(true);
					checkboxlistCalendarScroll.setVisible(false);
					checkboxlistBooksScroll.setVisible(true);
					removeCalendar.setVisible(false);
					removeBook.setVisible(true);

					ids.clear();

					for (int i = 0; i < dlmBooks.size(); i++) {
						JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmBooks
								.get(i);
						if (temp.isSelected() == true) {
							CheckboxBook temp2 = (CheckboxBook) temp
									.getObject();
							ids.add(temp2.getIdBooks());
						}

					}
					try {
						idIntoLokalDB(ids);
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						JOptionPane
								.showMessageDialog(
										null,
										"Es konnte keine Verbindung zur Datenbank hergestellt werden",
										"Haaalt! Stop!",
										JOptionPane.ERROR_MESSAGE);
						e1.printStackTrace();
					}

					Kontakte.update();

				} else if (tabbedPane.getSelectedIndex() == 2) {
					checkboxlistCalendar.setVisible(true);
					checkboxlistBooks.setVisible(false);
					addCalendar.setVisible(true);
					addBook.setVisible(false);
					checkboxlistCalendarScroll.setVisible(true);
					checkboxlistBooksScroll.setVisible(false);
					removeCalendar.setVisible(true);
					removeBook.setVisible(false);

					ids.clear();
					for (int i = 0; i < dlmCalendar.size(); i++) {
						JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmCalendar
								.get(i);
						if (temp.isSelected() == true) {
							CheckboxCalendar temp2 = (CheckboxCalendar) temp
									.getObject();
							ids.add(temp2.getIdCalendar());
						}
					}

					try {
						idIntoLokalDB(ids);
					} catch (ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						JOptionPane
								.showMessageDialog(
										null,
										"Es konnte keine Verbindung zur Datenbank hergestellt werden",
										"Haaalt! Stop!",
										JOptionPane.ERROR_MESSAGE);
						e1.printStackTrace();
					}
				} else {
					checkboxlistCalendar.setVisible(false);
					checkboxlistBooks.setVisible(false);
					addCalendar.setVisible(false);
					addBook.setVisible(false);
					checkboxlistCalendarScroll.setVisible(false);
					checkboxlistBooksScroll.setVisible(false);
					removeCalendar.setVisible(false);
					removeBook.setVisible(false);
				}

			}
		};

		tabbedPane.addChangeListener(tabchange);

	}

	// ----------------------------------------ADDITIONAL-----METHODS------------------------------------------------->

	/**
	 * Erzeugt Kontextmenü für CalenderList
	 * 
	 * @param evt
	 *            Ausgeführtes Mouseevent
	 */
	public void showMenuCal(final MouseEvent evt) {

		JPopupMenu menu = new JPopupMenu();

		JMenuItem calenderBearbeiten = new JMenuItem("Kalender Bearbeiten");
		calenderBearbeiten.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {

				checkboxlistCalendar.setSelectedIndex(checkboxlistCalendar
						.locationToIndex(evt.getPoint()));

				JCheckBoxWithObject current = (JCheckBoxWithObject) dlmCalendar
						.get(checkboxlistCalendar.getSelectedIndex());
				CheckboxCalendar currentcal = (CheckboxCalendar) current
						.getObject();
				EditCalendar ec = new EditCalendar(mainInstance, currentcal);
				ec.setVisible(true);

			}
		});

		menu.add(calenderBearbeiten);

		menu.show(evt.getComponent(), evt.getX(), evt.getY());

	}

	/**
	 * Erzeugt Kontextmenü für BookList
	 * 
	 * @param evt
	 *            Ausgeführtes Mouseevent
	 */
	public void showMenuBook(final MouseEvent evt) {

		JPopupMenu menu = new JPopupMenu();

		JMenuItem bookBearbeiten = new JMenuItem("Adressbuch Bearbeiten");

		bookBearbeiten.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {

				checkboxlistBooks.setSelectedIndex(checkboxlistBooks
						.locationToIndex(evt.getPoint()));
				JCheckBoxWithObject current = (JCheckBoxWithObject) dlmBooks
						.get(checkboxlistBooks.getSelectedIndex());
				CheckboxBook currentcal = (CheckboxBook) current.getObject();
				EditBooks eb = new EditBooks(mainInstance, currentcal);
				eb.setVisible(true);

			}
		});

		menu.add(bookBearbeiten);

		JMenuItem sendMail = new JMenuItem(
				"Email an alle enthaltenen Kontakte senden");
		sendMail.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				checkboxlistBooks.setSelectedIndex(checkboxlistBooks
						.locationToIndex(evt.getPoint()));
				CheckboxBook temp = (CheckboxBook) ((JCheckBoxWithObject) checkboxlistBooks
						.getSelectedValue()).getObject();
				int idBook = temp.getIdBooks();
				String mailTo = "";

				try {
					ResultSet contacts = getContactsFromDb(idBook);

					while (contacts.next()) {

						if (!contacts.getString("email").equals("")) {
							if (contacts.isLast()) {
								mailTo = mailTo + contacts.getString("email");
							} else {
								mailTo = mailTo + contacts.getString("email")
										+ ", ";
							}

						}

					}

				} catch (SQLException e1) {
					JOptionPane
							.showMessageDialog(
									null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e1.printStackTrace();
				}

				NewMailWindow nmw = new NewMailWindow(mailTo);
				nmw.setVisible(true);

			}

		});

		menu.add(sendMail);

		menu.show(evt.getComponent(), evt.getX(), evt.getY());

	}

	/**
	 * Testet ob ein Mouse Event ein Rechtsklick ist
	 * 
	 * @param e
	 *            Mause Event welches ausgeführt wurde
	 */
	private void evaluatePopupCal(MouseEvent e) {
		if (e.isPopupTrigger()) {
			showMenuCal(e);
		}
	}

	/**
	 * Testet ob ein Mouse Event ein Rechtsklick ist
	 * 
	 * @param e
	 *            Mause Event welches ausgeführt wurde
	 */
	private void evaluatePopupBook(MouseEvent e) {
		if (e.isPopupTrigger()) {
			showMenuBook(e);
		}
	}

	/**
	 * Funktion bekommt ein Bild und Maße übergeben und skaliert das Bild auf
	 * eben diese Maße
	 * 
	 * @param ret
	 *            Bild das skaliert werden soll
	 * @param w
	 *            Breite des Bildes, die es danach haben soll
	 * @param h
	 *            Höhe des Bildes, die es danach haben soll
	 * @return skaliertes Bild
	 */
	public Image resize(Image ret, int w, int h) {

		BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = tmp.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g2.drawImage(ret, 0, 0, w, h, null);
		g2.dispose();
		return tmp;
	}

	// ----Getter----&---Setter---------------------------------------------------------------------->

	public JPanel getKalender() {
		return kalender;
	}

	public void setKalender(JPanel kalender) {
		this.kalender = kalender;
	}

	public JTextField getCountNewMailsTextField() {
		return countNewMailsTextField;
	}

	public void setCountNewMailsTextField(JTextField countNewMailsTextField) {
		this.countNewMailsTextField = countNewMailsTextField;
	}

	public JTextField getCountNewEventsTextField() {
		return countNewEventsTextField;
	}

	public void setCountNewEventsTextField(JTextField countNewEventsTextField) {
		this.countNewEventsTextField = countNewEventsTextField;
	}

	public JTextField getCountNewTasksTextField() {
		return countNewTasksTextField;
	}

	public void setCountNewTasksTextField(JTextField countNewTasksTextField) {
		this.countNewTasksTextField = countNewTasksTextField;
	}

	public int getCountermails() {
		return countermails;
	}

	public void setCountermails(int countermails) {
		this.countermails = countermails;
	}

	public String getUser() {
		return this.user;
	}

	public String getPwd() {
		return this.pwd;
	}

	public static int getIdUser() {
		return iduser;
	}

	public static void setIduser(int iduser) {
		Test.iduser = iduser;
	}

	public static JPanel getLoadingPanel() {
		return loadingPanel;
	}

	@SuppressWarnings("static-access")
	public void setLoadingPanel(JPanel loadingPanel) {
		this.loadingPanel = loadingPanel;
	}

	public JProgressBar getProgressBar() {
		return progressBar;
	}

	public void setProgressBar(JProgressBar progressBar) {
		this.progressBar = progressBar;
	}

	public JPanel getLeftSideGroundPanel() {
		return leftSideGroundPanel;
	}

	public void setLeftSideGroundPanel(JPanel leftSideGroundPanel) {
		this.leftSideGroundPanel = leftSideGroundPanel;
	}

	public JTabbedPane getTabbedPane() {
		return tabbedPane;
	}

	public void setTabbedPane(JTabbedPane tabbedPane) {
		this.tabbedPane = tabbedPane;
	}

	private ViewMail viewMail;

	public ViewMail getViewMail() {
		return viewMail;
	}

	public void setViewMail(ViewMail viewMail) {
		this.viewMail = viewMail;
	}

	public ToDoPane getToDo() {
		return ToDo;
	}

	public void setToDo(ToDoPane toDo) {
		ToDo = toDo;
	}

	public AddContactPane getKontakte() {
		return Kontakte;
	}

	public void setKontakte(AddContactPane kontakte) {
		Kontakte = kontakte;
	}

	public void setProgressBarVisibleTrue() {

		getProgressBar().setVisible(true);
		getProgressBar().setIndeterminate(false);
		getProgressBar().setValue(100);
		forceRepaint();

	}

	public void setProgressBarVisibleFalse() {

		getLoadingPanel().remove(getProgressBar());
		getProgressBar().setVisible(false);
		forceRepaint();
		getLoadingPanel().add(getProgressBar());
		forceRepaint();
	}

	public LinkedList<Integer> getIds() {
		return ids;
	}

	public void setIds(LinkedList<Integer> ids) {
		this.ids = ids;
	}

	public void forceRepaint() {
		paint(getGraphics());
	}

	public int getR() {
		return r;
	}

	public void setR(int r) {
		this.r = r;
	}

	public int getG() {
		return g;
	}

	public void setG(int g) {
		this.g = g;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	// ////////////////////////////////// DATENBANKABFRAGEN
	// ///////////////////////////////////////////////

	/**
	 * Stellt Verbindung zur Datenbank her
	 * 
	 * @return
	 */
	// public boolean connect() {
	//
	// try {
	// Class.forName("com.mysql.jdbc.Driver");
	// connection = DriverManager
	// .getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
	//
	// } catch (ClassNotFoundException e) {
	//
	// e.printStackTrace();
	// } catch (SQLException e) {
	// JOptionPane.showMessageDialog(null,
	// "Es konnte keine Verbindung zur Datenbank hergestellt werden",
	// "Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
	// e.printStackTrace();
	// return false;
	// }
	//
	// return true;
	// }

	/**
	 * Holt alle Buecher eines Users aus DB
	 * 
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getBooksFromDB() throws SQLException {
		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Books.* FROM Books WHERE idUser = "
						+ Test.iduser + ";");

		return rs;

	}

	/**
	 * Holt alle Kalender eines Users aus DB
	 * 
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getCalendarsFromDB() throws SQLException {
		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Calendar.* FROM Calendar WHERE idUser = "
						+ Test.iduser + " AND Calendar.accepted = 1;");

		return rs;
	}

	/**
	 * Gibt RS mit allen Kontakten des Users und eines bestimmten Adressbuchs
	 * aus DB zurueck, sortiert nach idAdress
	 * 
	 * @return
	 * @throws SQLException
	 */
	public ResultSet getContactsFromDb(int idBooks) throws SQLException {

		Statement stat = connection.createStatement();

		stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

		ResultSet rs = stat
				.executeQuery("SELECT Adress.* FROM Adress, Entrys, Books, User where Adress.idAdress = Entrys.idAdress AND Entrys.idBooks = Books.idBooks AND Books.idUser = User.idUser AND User.idUser="
						+ Test.iduser
						+ " AND Entrys.idBooks = "
						+ idBooks
						+ " GROUP BY Adress.idAdress ORDER BY Adress.idAdress;");

		return rs;

	}

	/**
	 * Prüfung darauf ob man zu Kalendern eingeladen ist
	 * 
	 * @return Boolean true, wenn man eingeladen ist
	 * @throws SQLException
	 */
	@SuppressWarnings("unused")
	class checkforInvites extends TimerTask {

		@Override
		public void run() {
			LinkedList<Calendar> llcals = new LinkedList<Calendar>();
			boolean hasnewcal = false;

			Statement stat;
			try {
				stat = connection.createStatement();
				stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

				ResultSet rs = stat
						.executeQuery("SELECT Calendar.* FROM Calendar WHERE idUser = "
								+ Test.iduser + " AND Calendar.accepted = 0;");
				while (rs.next()) {
					llcals.add(new Calendar(rs.getInt("idCalendar"), rs
							.getString("name")));
					if (hasnewcal = false) {
						hasnewcal = true;
					}
				}

				for (int i = 0; i < llcals.size(); i++) {
					AddtoMyCals atmc = new AddtoMyCals(llcals.get(i),
							mainInstance);
					atmc.setVisible(true);
				}
			} catch (SQLException e) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}

		}

	}

	/**
	 * Connects to Lokal DB
	 * 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public void idIntoLokalDB(LinkedList<Integer> ids)
			throws ClassNotFoundException, SQLException {
		Class.forName("org.sqlite.JDBC");
		Connection conn = DriverManager
				.getConnection("jdbc:sqlite:checkids.db");
		Statement stat = conn.createStatement();
		stat.executeUpdate("drop table if exists ids;");
		stat.executeUpdate("create table if not exists ids (id);");

		PreparedStatement prep = conn
				.prepareStatement("insert into ids values (?);");

		for (int i = 0; i < ids.size(); i++) {
			prep.setInt(1, ids.get(i));
			prep.addBatch();
		}

		conn.setAutoCommit(false);
		prep.executeBatch();
		conn.setAutoCommit(true);

		ResultSet rs = stat.executeQuery("select * from ids;");

		while (rs.next()) {
			System.out.println("id = " + rs.getString("id"));

		}
		rs.close();
		conn.close();

	}

	public Date getNachoTempDate() {
		return nachoTempDate;
	}

	public void setNachoTempDate(Date nachoTempDate) {
		this.nachoTempDate = nachoTempDate;
	}

	public OptionReader getOR() {
		return or;
	}

	/**
	 * Datet die das Linke Panel up
	 * 
	 * @param reset
	 */
	public void updateLeftPane(boolean reset) {
		ids.clear();
		if (tabbedPane.getSelectedIndex() == 0) {
			if (reset == true) {
				try {
					dlmCalendar.clear();
					ResultSet calendars = getCalendarsFromDB();
					while (calendars.next()) {
						CheckboxCalendar calendar = new CheckboxCalendar(
								calendars.getInt("idCalendar"),
								calendars.getString("name"),
								calendars.getInt("idCreator"));

						JCheckBoxWithObject check = new JCheckBoxWithObject(
								calendar);
						dlmCalendar.addElement(check);
					}
					checkboxlistCalendar.selectAll();

				} catch (SQLException e) {
					JOptionPane
							.showMessageDialog(
									null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
				}
			}
			for (int i = 0; i < dlmCalendar.size(); i++) {
				JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmCalendar
						.get(i);
				if (temp.isSelected() == true) {
					CheckboxCalendar temp2 = (CheckboxCalendar) temp
							.getObject();
					ids.add(temp2.getIdCalendar());
				}

			}

			try {
				idIntoLokalDB(ids);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SQLException e1) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
			}

			updateCalendar();
		}
		if (tabbedPane.getSelectedIndex() == 1) {
			if (reset == true) {
				try {
					dlmBooks.clear();
					ResultSet books = getBooksFromDB();
					while (books.next()) {
						CheckboxBook book = new CheckboxBook(
								books.getInt("idBooks"),
								books.getString("name"),
								books.getInt("idCreator"));
						JCheckBoxWithObject check = new JCheckBoxWithObject(
								book);
						dlmBooks.addElement(check);
					}
					checkboxlistBooks.selectAll();
				} catch (SQLException e) {
					JOptionPane
							.showMessageDialog(
									null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
				}
			}

			for (int i = 0; i < dlmBooks.size(); i++) {
				JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmBooks
						.get(i);
				if (temp.isSelected() == true) {
					CheckboxBook temp2 = (CheckboxBook) temp.getObject();
					ids.add(temp2.getIdBooks());
				}

			}

			try {
				idIntoLokalDB(ids);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SQLException e1) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
			}
			Kontakte.setListselectionactivated(false);
			Kontakte.update();
			Kontakte.setListselectionactivated(true);
			forceRepaint();

		}
		if (tabbedPane.getSelectedIndex() == 2) {
			if (reset == true) {
				try {
					dlmCalendar.clear();
					ResultSet calendars = getCalendarsFromDB();
					while (calendars.next()) {
						CheckboxCalendar calendar = new CheckboxCalendar(
								calendars.getInt("idCalendar"),
								calendars.getString("name"),
								calendars.getInt("idCreator"));

						JCheckBoxWithObject check = new JCheckBoxWithObject(
								calendar);
						dlmCalendar.addElement(check);
					}
					checkboxlistCalendar.selectAll();
				} catch (SQLException e) {
					JOptionPane
							.showMessageDialog(
									null,
									"Es konnte keine Verbindung zur Datenbank hergestellt werden",
									"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
				}
			}

			for (int i = 0; i < dlmCalendar.size(); i++) {
				JCheckBoxWithObject temp = (JCheckBoxWithObject) dlmCalendar
						.get(i);
				if (temp.isSelected() == true) {
					CheckboxCalendar temp2 = (CheckboxCalendar) temp
							.getObject();
					ids.add(temp2.getIdCalendar());
				}

			}

			try {
				idIntoLokalDB(ids);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (SQLException e1) {
				JOptionPane
						.showMessageDialog(
								null,
								"Es konnte keine Verbindung zur Datenbank hergestellt werden",
								"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
			}

			if (sortedToDo == 0) {
				ToDo.setListselectionactivated(false);
				ToDo.update();
				ToDo.setListselectionactivated(true);
			}
			if (sortedToDo == 1) {
				ToDo.setListselectionactivated(false);
				ToDo.updateSorted();
				ToDo.setListselectionactivated(true);
			}

			forceRepaint();
		}
	}

	/**
	 * Datet den Kalender up
	 */
	public void updateCalendar() {
		click = (Date) calendarpanel.getValue();

		if (kalender instanceof CalView) {
			if (click == null) {
				click = ((CalView) kalender).getD();
			}
			((CalView) kalender).createCal(click, click);
		} else if (kalender instanceof WeekView) {
			if (click == null) {
				click = ((WeekView) kalender).getClickedDay();
			}
			((WeekView) kalender).setClickedDay(click);
			((WeekView) kalender).createWeekView();
		}

		forceRepaint();
	}

	/**
	 * Apple Only für FullScreen SUpport
	 * 
	 * @param window
	 */
	public static void enableFullScreenMode(Window window) {
		String className = "com.apple.eawt.FullScreenUtilities";
		String methodName = "setWindowCanFullScreen";

		try {
			Class<?> clazz = Class.forName(className);
			Method method = clazz.getMethod(methodName, new Class<?>[] {
					Window.class, boolean.class });
			method.invoke(null, window, true);
		} catch (Throwable t) {
			System.err.println("Full screen mode is not supported");
			t.printStackTrace();
		}
	}

}
